<template>
  <div class="">
    <sticky :class-name="'sub-navbar '+status" style="margin-bottom:20px;background-color:#fff;">
      <el-button type="info" @click="returnPage">返回</el-button>
      <el-button type="primary" @click="updateArticleClicked">保存更新</el-button>
    </sticky>
    <el-form class="demo-form-inline">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="title">
            <MDinput v-model="article.title" :maxlength="100" name="name" required>标题</MDinput>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item label-width="45px" prop="title" label="作者">
            <el-input v-model="article.author"
              placeholder="作者"
              clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="分类">
            <el-select v-model="article.classify_id" style="width: 140px" placeholder="选择分类">
              <el-option v-for="item in classifyList" :key="item.id" :label="item.title" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="公众号名称">{{article.wechat_name}}</el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="公众号">{{article.wechat_id}}</el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="首图">
            <el-upload
              class="cover-upload"
              :action="`${prefixUrl}/fileUpload`"
              list-type="picture-card"
              name="files"
              :limit="1"
              :data="{type:'cover',classify_id:article.classify_id,article_id:article.id}"
              :file-list="coverImgs"
              :on-preview="handlePictureCardPreview"
              :on-success="successCoverImg"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <el-form-item label="文章列表图片"></el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item>
            <el-button size="mini" @click="changeArticleImgClicked">随机更换</el-button>
          </el-form-item>
        </el-col>

        <el-col :span="2">
          <el-form-item>
            <el-button type="info" size="mini" @click="resetArticleClicked">还原最初列表图</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item placeholder="fffff">
            <el-upload
              action="https://jsonplaceholder.typicode.com/posts/"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :file-list="storeImgs"
              :on-remove="handleRemove">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item prop="content_html" style="margin-bottom: 30px;">
            <Tinymce ref="editor" :height="400" v-model="article.content_html"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog :visible.sync="coverDialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import Tinymce from '@/components/Tinymce'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import MDinput from '@/components/MDinput'
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";
  import ElFormItem from "../../../node_modules/element-ui/packages/form/src/form-item.vue";
  import {classifyList} from '@/api/classify'
  import {articleDetailPost, resetArticle, changeArticleImgs, updateArticleByElas } from '@/api/article'
  import Vue from 'vue'



  export default {
    data() {
      return {
        article: {
          classifyId: null,
        },
        coverImgs: [],
        storeImgs: [],
        status: 'draft',
        classifyList: [],
        coverDialogVisible: false,
        classifyIsLoad: false,
        prefixUrl: process.env.BASE_API


      }
    },
    components: {
      ElFormItem,
      ElCol,
      ElRow,
      Tinymce,
      MDinput, Sticky
    },
    methods: {
      onSubmit() {
        console.log('submit!');
      },
      // 分类列表
      getClassifyList(callFn, id) {
        classifyList().then(response => {
          this.classifyList = response.data.data
          if (callFn && typeof callFn === 'function') {
            callFn(id)
          }
        })
      },

      successCoverImg(rep){
        var url = ''
        for(let i in rep.result){
          url = rep.result[i]
        }

        if(!url) {
          return
        }

        this.coverImgs = [{name:'',url:`${this.prefixUrl}/${url}`}]
        this.article.cover = url
      },

      handleRemove(file, fileList) {
        console.log(file, fileList)
      },

      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.coverDialogVisible = true
      },

      //返回上一个页面
      returnPage(){
        this.$router.go(-1)
      },

      //设置文章图片集合
      setArticleStoreImgs(store_imgs){
        this.storeImgs = []
        if (store_imgs && store_imgs.length > 0) {
          for (var i = 0; i < store_imgs.length; i++) {
            var s_img = store_imgs[i]
            store_imgs[i] = `${this.prefixUrl}/${s_img}`
            this.storeImgs.push({name: '', url: `${this.prefixUrl}/${s_img}`})
          }
        }
      },

      //文章详情
      articleDetail(id) {
        articleDetailPost({id: id}).then(response => {
          var article = response.data.data
          if (article.cover) {
            article.cover = `${this.prefixUrl}/${article.cover}`
            this.coverImgs.push({name: '', url: article.cover})
          }

          this.setArticleStoreImgs(article.store_imgs)

          if (article.content_html) {
            article.content_html = this.changeContentImgSrc(article.content_html)
          }

          this.article = article
        })
      },

      //还原文章图片
      resetArticleClicked(){
        this.$confirm('此操作还原文章图片, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resetArticle({id:this.article.id}).then(response => {
            var article = response.data.data.data
            this.setArticleStoreImgs(article.store_imgs)
            if (article.content_html) {
              article.content_html = this.changeContentImgSrc(article.content_html)
              Vue.set(this.article,'content_html',article.content_html)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消还原'
          })
        })
      },

      //更新文章
      updateArticleClicked(){

        updateArticleByElas(this.article).then(response => {
//          var article = response.data.data.data
        })
      },

      //随机切换文章图片
      changeArticleImgClicked(){
        this.$confirm('此操作随机切换文章图片, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          changeArticleImgs({id:this.article.id,classify_id:this.article.classify_id}).then(response => {
            var article = response.data.data.data
            this.setArticleStoreImgs(article.store_imgs)
            if (article.content_html) {
              article.content_html = this.changeContentImgSrc(article.content_html)
              Vue.set(this.article,'content_html',article.content_html)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消切换'
          })
        })
      },

      //替换图片地址
      changeContentImgSrc(content) {
        var self = this
        return content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {
          return `<img src="${self.prefixUrl}/${capture}" data-src="${self.prefixUrl}/${capture}" />`
        })
      },

      // 加载数据
      initLoadData(id) {
        if (!this.classifyIsLoad) {
          this.getClassifyList(this.articleDetail, id)
          this.classifyIsLoad = true
        } else {
          this.articleDetail(id)
        }
      },
    },
    created() {
      this.initLoadData(this.$route.params.id)
    }
  }
</script>

<style>
  .article-navbar {
    margin-bottom: 20px;
  }

  .demo-form-inline {
    padding: 10px 15px;
  }

  .a-title {
    width: 500px;
  }

  .el-upload-list--picture-card .el-upload-list__item {
    width: 80px;
    height: 80px;
  }

  .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 90px;
  }
</style>
